import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  cid: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_CID: (state, cid) => {
    state.cid = cid
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        // const { data } = response.data
        // if(response.data.data.admin==0){
          const { data } = response.data
          commit('SET_TOKEN', data.userName)
          commit('SET_CID', data.userCode)
          commit('SET_AVATAR', data.userUrl)
          sessionStorage.setItem("cuserName",data.userName)
          sessionStorage.setItem("cid",data.userCode)
          sessionStorage.setItem("admin",data.admin)
          setToken(data.userCode)
          resolve()
      //  }else{
      //   this.$message.error('登录失败！');
      //  }
      }).catch(error => {
        console.log(error);
        reject(error)
      })
    })
  },

  // get user info
  // getInfo({ commit, state }) {    
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.cid).then(response => {
  //       const { data } = response.data
  //       if (!data) {
  //         reject('Verification failed, please Login again.')
  //       }

  //       console.log(data);
        
  //       const { cUserName } = data.cuserName
  //       console.log(data.cuserName);
        
  //       commit('SET_NAME', cUserName)
  //       commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
  //       resolve(data)
  //     }).catch(error => {
  //       console.log(error);
  //       reject(error)
  //     })
  //   })
  // },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      removeToken()
      resetRouter()
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}